/*
 * @brief 空气质量传感器
 */

#include <rtthread.h>
#include <rtdevice.h>

#include <sensor_mp503.h>

#define DBG_TAG "mp503.c"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

rt_adc_device_t adc_dev = RT_NULL;

/**
 * @brief  空气质量、烟雾使用ADC设备初始化
 * @param  无
 * @return -1 -> ADC设备使能失败。other -> ADC设备使能成功
 */
int adc_init(void)
{
    adc_dev = (rt_adc_device_t) rt_device_find(ADC_DEV_NAME);
    if (adc_dev == RT_NULL)
    {
        LOG_E("failed to find %s device!\n", ADC_DEV_NAME);
        return -1;
    }

    if ((rt_adc_enable(adc_dev, AIR_ADC_CHANNEL) == RT_EOK) && (rt_adc_enable(adc_dev, GAS_ADC_CHANNEL) == RT_EOK))
    {
        return 0;
    }

    return -1;
}

/**
 * @brief  获取空气质量传感器值
 * @param  要获取的传感器通道
 * @return -1 -> ADC设备未打开。other -> ADC值
 */
int adc_getVal(unsigned char channel)
{
    if (adc_dev != RT_NULL)
    {
        int value = 0;
        if (channel == AIR_ADC_CHANNEL || channel == GAS_ADC_CHANNEL)
        {
            value = rt_adc_read(adc_dev, channel);
            return value;
        }
    }

    LOG_E("ADC drive not open!\n");

    return -1;
}

/**
 * @brief  关闭空气质量ADC采集
 * @param  无
 * @return -1 -> 关闭失败； 0 -> 关闭成功
 */
int adc_close(void)
{
    if (adc_dev == RT_NULL)
    {
        LOG_E("ADC drive not on!\n");
        return -1;
    }

    rt_err_t result = RT_ERROR;
    if (rt_adc_enable(adc_dev, AIR_ADC_CHANNEL) == RT_EOK && rt_adc_enable(adc_dev, GAS_ADC_CHANNEL) == RT_EOK)
    {
        result = RT_EOK;
    }

    if (result == RT_EOK)
        adc_dev = RT_NULL;

    return result;
}
